//
//  MainTabBarController.m
//  FieldStory
//
//  Created by itte on 2017/6/23.
//  Copyright © 2017年 funmain. All rights reserved.
//

#import "MainTabBarController.h"
#import "MainTabBar.h"
#import "MainNavigationController.h"
#import "FSIngredientsVC.h"
#import "FSLoginVC.h"

@interface MainTabBarController ()<MainTabBarDelegate>
@property(nonatomic, weak)MainTabBar *mainTabBar;
@end

@implementation MainTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self SetupMainTabBar];
    [self SetupAllControllers];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    for (UIView *child in self.tabBar.subviews) {
        if ([child isKindOfClass:[UIControl class]]) {
            [child removeFromSuperview];
        }
    }
}

- (void)SetupMainTabBar{
    MainTabBar *mainTabBar = [[MainTabBar alloc] init];
    mainTabBar.frame = self.tabBar.bounds;
    mainTabBar.delegate = self;
    [self.tabBar addSubview:mainTabBar];
    _mainTabBar = mainTabBar;
}

- (void)SetupAllControllers
{
    // FSIngredientsVC
    NSArray *tabClassArray = @[@"FSHomePageVC",@"FSStoryVC",@"FSProfileVC"];
    NSArray *titles = @[@"", @"", @""];
    NSArray *seletedImageArray = @[@"tabba01_sel",@"tabba03_sel",@"tabba04_sel"];
    NSArray *imageArray = @[@"tabba01_nor",@"tabba03_nor",@"tabba04_nor"];
    for (int i=0; i<tabClassArray.count; i++) {
        UIViewController *childVc = [[NSClassFromString(tabClassArray[i]) alloc] initWithNibName:nil bundle:nil];
        [self setupChildVc:childVc title:titles[i] image:imageArray[i] selectedImage:seletedImageArray[i]];
    }
}

- (void)setupChildVc:(UIViewController *)childVc title:(NSString *)title image:(NSString *)imageName selectedImage:(NSString *)selectedImageName{
    MainNavigationController *nav = [[MainNavigationController alloc] initWithRootViewController:childVc];
    childVc.tabBarItem.image = [UIImage imageNamed:imageName];
    childVc.tabBarItem.selectedImage = [UIImage imageNamed:selectedImageName];
    childVc.tabBarItem.title = title;
    [self.mainTabBar addTabBarButtonWithTabBarItem:childVc.tabBarItem];
    [self addChildViewController:nav];
}



#pragma mark - MainTabBarDelegate
- (void)tabBar:(MainTabBar *)tabBar didSelectedButtonFrom:(long)fromBtnTag to:(long)toBtnTag{
    self.selectedIndex = toBtnTag;
}

- (void)tabBarClickWriteButton:(MainTabBar *)tabBar{
    if(![FSLogin sharedInstance].isLogined){
        FSLoginVC *loginVC = [[FSLoginVC alloc] init];
        [self presentViewController:loginVC animated:YES completion:nil];
        return ;
    }
    FSIngredientsVC *ingredientsVC = [[FSIngredientsVC alloc] init];
    UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:ingredientsVC];
    [self presentViewController:nvc animated:YES completion:nil];
}
@end
